import {
  dictDataPageApi,
  addDictDataApi,
  editDictDataApi,
  delDictDataApi
} from '@/api/system/dict'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'

type props = {
  id: number
  type: string
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  drawerShow: Ref<boolean>
  dictDataForm: Ref<{ [index: string]: any }>
  proTableInst: Ref<ProTableInst | null>
}

export const useDictDataApi = ({
  id,
  type,
  handleType,
  handleTag,
  drawerShow,
  dictDataForm,
  proTableInst
}: props) => {
  const confirmLoading = ref(false)

  // 获取字典列表
  const fetchDictDataPage = async (pageRequest, queryParams) => {
    try {
      const res = await dictDataPageApi({
        ...queryParams,
        pageRequest,
        type,
        id
      })

      if (res.code === '0000') {
        return {
          data: res.data?.content,
          total: res.data?.total
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增or修改字典
  const fetchAddOrEditDictData = async () => {
    try {
      confirmLoading.value = true
      const fetch =
        handleType.value === 'add' ? addDictDataApi : editDictDataApi
      const res = await fetch({
        ...dictDataForm.value,
        type
      })
      if (res.code === '0000') {
        window['$message'].success(handleTag.value + '成功')
        proTableInst.value?.reload()
        drawerShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除字典
  const fetchDelDictData = async (id) => {
    try {
      const res = await delDictDataApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchDictDataPage,
    fetchAddOrEditDictData,
    fetchDelDictData
  }
}
